<template>
  <el-dialog
    v-model="dialogVisible"
    title="重置密码"
    width="400px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="reset-password-form"
    >
      <el-form-item label="用户名">
        <el-input :value="userData?.userName" disabled />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  resetUserPasswordApi,
  getUserId,
  type UserInfo,
  type ResetPasswordRequest
} from "@/api/user-management";

interface Props {
  visible: boolean;
  userData: UserInfo | null;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const formRef = ref<FormInstance>();
const loading = ref(false);
const dialogVisible = ref(false);

// 表单数据
const form = reactive({
  newPassword: "",
  confirmPassword: ""
});

// 自定义验证函数
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== form.newPassword) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

// 表单验证规则
const rules: FormRules = {
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: "blur" }
  ]
};

// 监听visible变化
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val) {
      nextTick(() => {
        resetForm();
      });
    }
  }
);

// 监听dialogVisible变化
watch(dialogVisible, val => {
  emit("update:visible", val);
});

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    newPassword: "",
    confirmPassword: ""
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value || !props.userData) return;

  try {
    await formRef.value.validate();

    loading.value = true;

    console.log("=== 重置密码调试信息 ===");
    console.log("props.userData:", props.userData);
    console.log("props.userData的所有属性:", Object.keys(props.userData));
    console.log("props.userData.userId:", props.userData.userId);
    console.log("props.userData.id:", props.userData.id);

    const userId = getUserId(props.userData);
    console.log("getUserId返回的结果:", userId);

    if (!userId || userId === 0) {
      console.error("❌ 用户ID验证失败，尝试从其他字段获取");
      console.error("userData内容:", JSON.stringify(props.userData, null, 2));

      // 尝试直接从userData中获取可能的ID字段
      let fallbackUserId = 0;
      const idFields = ["userId", "id", "user_id", "ID", "User_ID"];

      for (const field of idFields) {
        const value = props.userData[field];
        if (value && !isNaN(Number(value)) && Number(value) > 0) {
          fallbackUserId = Number(value);
          console.log(`🔄 从字段 ${field} 获取到备用ID: ${fallbackUserId}`);
          break;
        }
      }

      if (fallbackUserId > 0) {
        console.log("✅ 使用备用用户ID:", fallbackUserId);
        // 使用备用ID继续执行
        const resetData: ResetPasswordRequest = {
          newPassword: form.newPassword,
          confirmPassword: form.confirmPassword
        };

        console.log("重置密码 - resetData:", resetData);
        console.log(
          "调用API:",
          `resetUserPasswordApi(${fallbackUserId}, resetData)`
        );

        const response = await resetUserPasswordApi(fallbackUserId, resetData);
        console.log("重置密码 - API响应:", response);

        if (response.code === 200) {
          ElMessage.success("密码重置成功");
          emit("success");
        } else {
          ElMessage.error(response.message || "密码重置失败");
        }
        loading.value = false;
        return;
      } else {
        ElMessage.error("用户ID不能为空，请检查控制台日志");
        loading.value = false;
        return;
      }
    }

    console.log("✅ 用户ID验证通过:", userId);

    const resetData: ResetPasswordRequest = {
      newPassword: form.newPassword,
      confirmPassword: form.confirmPassword
    };

    console.log("重置密码 - resetData:", resetData);
    console.log("调用API:", `resetUserPasswordApi(${userId}, resetData)`);

    const response = await resetUserPasswordApi(userId, resetData);
    console.log("重置密码 - API响应:", response);

    if (response.code === 200) {
      ElMessage.success("密码重置成功");
      emit("success");
    } else {
      ElMessage.error(response.message || "密码重置失败");
    }
  } catch (error) {
    console.error("重置密码失败:", error);
    ElMessage.error("重置密码失败");
  } finally {
    loading.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.reset-password-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
